package logic
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	
	import httpserver.HttpRequest;
	import httpserver.WebServerConnection;
	
	import logic.user.LocalUser;
	import logic.user.User;
	import logic.user.UserAuthority;
	
	import tools.json.JSON;
	import tools.json.JSONParseError;

	
	public class PPTControlManager extends EventDispatcher
	{
		//事件类型声明
		public static const USER_LOGIN_SUCCESS:String = "UserLoginSuccess";
		public static const USER_LOGIN_FAILED:String = "UserLoginFailed";
		public static const USER_REGISTER_RESULT:String = "UserRegisterResult";
		public static const USER_RECOVER_PASSWORD_RESULT:String = "UserRecoverPasswordResult";
		public static const PPT_CONTROL_RESULT:String = "PPTControlResult";
		public static const INTERNET_REQUEST_ERROR:String = "internet_request_error";
		
		// PPT控制操作类型
		public static const PPTCONTROL_LEFT:String = "Left";
		public static const PPTCONTROL_RIGHT:String = "Right";
		public static const PPTCONTROL_MOUSEMOVE:String = "MouseMove";
		public static const PPTCONTROL_MOUSELOCATE:String = "Location";
		public static const PPTCONTROL_NORESPONSE:String = "NoResoponse";
		public static const PPTCONTROL_WAITRESPONSE:String = "WaitForResponse";
		public static const PPTCONTROL_ZOOMIN:String = "ZoomIn";
		public static const PPTCONTROL_ZOOMOUT:String = "ZoomOut";
		
		//const for control response messages
		public static const CONTROLACK_SUCCESS:String = "SUCCESS";
		public static const CONTROLACK_FAILURE:String = "FAILURE";
		public static const CONTROLACK_NORESPONSE:String = "NORESPONSE";
		public static const CONTROLACK_NOTLOGIN:String = "NOTLOGIN";
		
		//web 服务器的url
		private var _webUrl:String = "http://localhost:31103/";
		//private var _webUrl:String = "http://192.168.0.162:8081/";
		private var _loginUrl:String = _webUrl + "Login.aspx";
		private var _logoutUrl:String = _webUrl + "Logout.aspx";
		private var _userRegisterUrl:String = _webUrl + "UserRegister.aspx";
		private var _passwordRecoverUrl:String = _webUrl + "RetrieveUserPassword.aspx";
		private var _pptControlUrl:String = _webUrl + "ControlRequest.aspx";
		
		// const for login response messages
		private static const SOURCETYPE_MOBILE:String = "mobile";
		private static const LOGINACK_SUCCESS:String = "SUCCESS";
		private static const LOGINACK_FAIL:String = "FAIL";
		private static const LOGINACK_REDIRECT:String = "REDIRECT";
		
		private var _localUser:LocalUser = null;
		private var _proxy:IProxy = null;
		
		public function PPTControlManager(target:IEventDispatcher=null)
		{
			super(target);
			
			_localUser = new LocalUser();
		}
		
		public function createProxy():void
		{
			_proxy = new HttpProxy();
			_proxy.init();
		}
		
		public function setURL(url:String):void
		{
			_webUrl = url;
			_loginUrl = _webUrl + "Login.aspx";
			_logoutUrl = _webUrl + "Logout.aspx";
			_userRegisterUrl = _webUrl + "UserRegister.aspx";
			_passwordRecoverUrl = _webUrl + "RetrieveUserPassword.aspx";
			_pptControlUrl = _webUrl + "ControlRequest.aspx";
		}
		
		public function userLogin(email:String, password:String):void
		{
			var loginPar:Object = new Object();
			loginPar.Versions = 1.0;
			loginPar.UserName = email;
			loginPar.Password = password;
			loginPar.SourceType = SOURCETYPE_MOBILE;
			_loginUrl = _webUrl+"login.aspx";
			_proxy.sendRequest(_loginUrl, loginPar, onLoginResult);
			
			_localUser.email = email;
			_localUser.password = password;
		}
		
		public function userLogout(email:String):void
		{
			var logoutPar:Object = new Object();
			logoutPar.UserName = email;
			
			_proxy.sendRequest(_logoutUrl, logoutPar, onLogoutResult);
		}
		
		public function userRegister(email:String, password:String, nickName:String):void
		{
			var registerPar:Object = new Object();
			registerPar.UserName = email;
			registerPar.Password = password;
			registerPar.NickName = nickName;
			
			_proxy.sendRequest(_userRegisterUrl, registerPar, onRegisterResult);
		}
		
		public function userPasswordRecover(email:String):void
		{
			var passwordRecoverPar:Object = new Object();
			passwordRecoverPar.UserName = email;
			
			_proxy.sendRequest(_passwordRecoverUrl, passwordRecoverPar, onPasswordRecoverResult);		
		}
		
		private function onLoginResult(jsonData:String):void
		{
			var resObj:Object;
			var resJson:String = jsonData;
			var paramObj:Object;
			
			resObj = jsonDecode(resJson);
			if (resObj == null)
			{
				dispatchPPTControlEvent(USER_LOGIN_FAILED);
				return;
			}
			
			if (resObj.AckCode == LOGINACK_SUCCESS)
			{
				//创建用户权限
				//var userAuthority:UserAuthority = new UserAuthority();
				//userAuthority.connectionType = resObj.ConnectionType as Array;
				
				//_localUser.authority = userAuthority;
				
				//_currentState = _currentState.userLoginEvent(); //发送用户登录事件改变当前状态
				//addCameraStateEvent(_currentState);
				dispatchPPTControlEvent(USER_LOGIN_SUCCESS);
			}
			else if (resObj.AckCode == LOGINACK_REDIRECT)
			{
				// redirect to new url				
			}
			else if (resObj.AckCode == LOGINACK_FAIL)
			{
				//分发用户登录失败事件
				paramObj = new Object();
				paramObj.Result = resObj.DetailMessage;
				
				dispatchPPTControlEvent(USER_LOGIN_FAILED, paramObj);
			}
			else
			{
				// unknown error
				paramObj = new Object();
				paramObj.Result = resObj.DetailMessage;
				dispatchPPTControlEvent(USER_LOGIN_FAILED, paramObj);
			}
			
		}
		
		private function onLogoutResult(jsonData:String):void
		{
			
		}
		
		private function onRegisterResult(jsonData:String):void
		{
			var resObj:Object;
			
			resObj = jsonDecode(jsonData);
			dispatchPPTControlEvent(USER_REGISTER_RESULT, resObj);
		}
		
		private function onPasswordRecoverResult(jsonData:String):void
		{
			var resObj:Object;
			
			resObj = jsonDecode(jsonData);
			if (resObj == null)
			{
				dispatchPPTControlEvent(USER_RECOVER_PASSWORD_RESULT);
				return;
			}
			dispatchPPTControlEvent(USER_RECOVER_PASSWORD_RESULT, resObj);
		}
		
		public function controlPPT(operation:String):void
		{
			var para:Object = new Object();
			para.Versions = 1.0;
			para.Uid = 0;
			para.Seq = 0;
			para.Operation = operation;
			para.Process = PPTCONTROL_WAITRESPONSE;
			
			_proxy.sendRequest(_pptControlUrl, para, onPPTControlResult);
		}
		
		private function onPPTControlResult(jsonData:String):void
		{
			var resObj:Object;
			
			resObj = jsonDecode(jsonData);
			if (resObj != null)
			{
				dispatchPPTControlEvent(PPT_CONTROL_RESULT, resObj);
			}
		}
		
		
		public function moveMouse(offsetX:Number, offsetY:Number):void
		{
			//避免服务器负载过重。
			if(!_proxy.requestFinished())
				return;
			
			var para:Object = new Object();
			para.Versions = 1.0;
			para.Uid = 0;
			para.Seq = 0;
			para.Operation = PPTCONTROL_MOUSEMOVE;
			para.OffsetX = offsetX;
			para.OffsetY = offsetY;
			para.Process = PPTCONTROL_NORESPONSE;
			
			
			_proxy.sendRequest(_pptControlUrl, para, onPPTControlResult);
			
			trace("mouse move");
		}
		
		/**
		 *offsetx，y都是normalized之后的值，是相对整体的比例。 
		 * @param offsetX
		 * @param offsetY
		 * 
		 */
		public function locateMouse(offsetX:Number, offsetY:Number):void
		{
			//避免服务器负载过重。
			if(!_proxy.requestFinished())
				return;
			
			var para:Object = new Object();
			para.Versions = 1.0;
			para.Uid = 0;
			para.Seq = 0;
			para.Operation = PPTCONTROL_MOUSELOCATE;
			para.OffsetX = offsetX;
			para.OffsetY = offsetY;
			para.Process = PPTCONTROL_NORESPONSE;
			
			
			_proxy.sendRequest(_pptControlUrl, para, onPPTControlResult);
			
			trace("mouse locate");
		}
		
		public function ZoomIn():void
		{
			var para:Object = new Object();
			para.Versions = 1.0;
			para.Uid = 0;
			para.Seq = 0;
			para.Operation = PPTCONTROL_ZOOMIN;
			para.Process =  PPTCONTROL_NORESPONSE ;// PPTCONTROL_WAITRESPONSE;
			
			_proxy.sendRequest(_pptControlUrl, para, onPPTControlResult);
			
			trace("zoomIn");
		}	
		
		public function ZoomOut():void
		{
			var para:Object = new Object();
			para.Versions = 1.0;
			para.Uid = 0;
			para.Seq = 0;
			para.Operation = PPTCONTROL_ZOOMOUT;
			para.Process = PPTCONTROL_NORESPONSE //PPTCONTROL_WAITRESPONSE;
			
			_proxy.sendRequest(_pptControlUrl, para, onPPTControlResult);
			
			trace("zoomOut");
		}		
		
		private function dispatchPPTControlEvent(eventType:String,dataObj:Object=null):void
		{
			var pptControlEvent:PPTControlEvent;
			pptControlEvent = new PPTControlEvent(eventType, dataObj);
			dispatchEvent(pptControlEvent);
		}
		
		private function jsonDecode(jsonStr:String):Object
		{
			var resObj:Object = null;
			try
			{
				resObj = tools.json.JSON.decode(jsonStr)
			} 
			catch(error:JSONParseError) 
			{
				//json解析出错
			}
			
			return resObj;
		}
	}
}